﻿// Decompiled with JetBrains decompiler
// Type: MCM.LightInject.ImmutableMapTreeExtensions
// Assembly: MCMv5, Version=5.10.2.0, Culture=neutral, PublicKeyToken=null
// MVID: 7AB326B9-B2B4-41C2-9177-68E944071101
// Assembly location: D:\steam\steamapps\workshop\content\261550\2859238197\bin\Win64_Shipping_Client\MCMv5.dll

using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;

#nullable disable
namespace MCM.LightInject
{
  [ExcludeFromCodeCoverage]
  internal static class ImmutableMapTreeExtensions
  {
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static TValue Search<TValue>(this ImmutableMapTree<TValue> tree, int key)
    {
      while (tree.Height != 0 && tree.Key != key)
        tree = key < tree.Key ? tree.Left : tree.Right;
      return !tree.IsEmpty ? tree.Value : default (TValue);
    }

    public static ImmutableMapTree<TValue> Add<TValue>(
      this ImmutableMapTree<TValue> tree,
      int key,
      TValue value)
    {
      if (tree.IsEmpty)
        return new ImmutableMapTree<TValue>(key, value, tree, tree);
      if (key > tree.Key)
        return ImmutableMapTreeExtensions.AddToRightBranch<TValue>(tree, key, value);
      return key < tree.Key ? ImmutableMapTreeExtensions.AddToLeftBranch<TValue>(tree, key, value) : new ImmutableMapTree<TValue>(key, value, tree);
    }

    private static ImmutableMapTree<TValue> AddToLeftBranch<TValue>(
      ImmutableMapTree<TValue> tree,
      int key,
      TValue value)
    {
      return new ImmutableMapTree<TValue>(tree.Key, tree.Value, tree.Left.Add<TValue>(key, value), tree.Right);
    }

    private static ImmutableMapTree<TValue> AddToRightBranch<TValue>(
      ImmutableMapTree<TValue> tree,
      int key,
      TValue value)
    {
      return new ImmutableMapTree<TValue>(tree.Key, tree.Value, tree.Left, tree.Right.Add<TValue>(key, value));
    }
  }
}
